package com.itheima.zxingdemo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.ai.cv.common.ConnectionCallback;
import ohos.ai.cv.common.VisionManager;
import ohos.ai.cv.qrcode.IBarcodeDetector;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

public class MainDemoAbility extends Ability implements Component.ClickedListener{

    static final HiLogLabel label=new HiLogLabel(HiLog.LOG_APP,0x0001,"demo");
    private Button mBtn1;
    private TextField mEt;
    private Button mBtn2,mBtn3;
    private Image mImage;
    private final static int REQ_CODE = 1028;
    private Context mContext;
    private Text mTvResult;
    private Image mImageCallback;
    ConnectionCallback connectionCallback;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        super.setMainRoute(MainDemoAbilitySlice.class.getName());
        super.setUIContent(ResourceTable.Layout_ability_main_demo);
//        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        connectionCallback = new ConnectionCallback() {
            @Override
            public void onServiceConnect() {
                //连接成功生成二维码
                generateQrCode();
            }


            @Override
            public void onServiceDisconnect() {
                // Do something when service connects unsuccessfully
            }
        };
        initView();
        mContext = this;
    }
    private void initView() {
        mBtn1 = (Button) findComponentById(ResourceTable.Id_btn1);
        mBtn1.setClickedListener(this);
        mEt = (TextField) findComponentById(ResourceTable.Id_et);
        mBtn2 = (Button) findComponentById(ResourceTable.Id_btn2);
        mBtn2.setClickedListener(this);
        mBtn3 = (Button) findComponentById(ResourceTable.Id_camera);
        mBtn3.setClickedListener(this);
        mImage = (Image) findComponentById(ResourceTable.Id_image);
        mImage.setClickedListener(this);
        mTvResult = (Text) findComponentById(ResourceTable.Id_tv_result);
        mTvResult.setClickedListener(this);
        mImageCallback = (Image) findComponentById(ResourceTable.Id_image_callback);
        mImageCallback.setClickedListener(this);
    }
    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_btn1:
                Intent intent1 = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName("com.itheima.zxingdemo")
                        .withAbilityName("com.google.zxing.CaptureAbility")
                        .build();
                intent1.setOperation(operation);
                startAbility(intent1);
                break;
            case ResourceTable.Id_camera:
                Intent intentCamera = new Intent();
                Operation operationCamera = new Intent.OperationBuilder()
                        .withBundleName("com.itheima.zxingdemo")
                        .withAbilityName("com.itheima.zxingdemo.CameraDemo")
                        .build();
                intentCamera.setOperation(operationCamera);
                startAbility(intentCamera);
                break;
            case ResourceTable.Id_btn2:
                mImage.setVisibility(Component.VISIBLE);
                //隐藏扫码结果view
                mImageCallback.setVisibility(Component.HIDE);
                mTvResult.setVisibility(Component.HIDE);
                //初始化
                int initResult = VisionManager.init(this, connectionCallback);
                HiLog.info(label, "初始化结果"+initResult);
                break;
        }
    }

    private void showToast(String msg) {
        new ToastDialog(this).setContentText(msg).show();
    }
    /**
     * 用字符串生成二维码
     *
     */
    private void generateQrCode() {
        //获取需要生成的内容
        String content = mEt.getText().toString().trim();
        //获取二维码侦测器
        IBarcodeDetector barcodeDetector = VisionManager.getBarcodeDetector(this);
        final int SAMPLE_LENGTH = 500;
        byte[] byteArray = new byte[SAMPLE_LENGTH * SAMPLE_LENGTH * 4];
        int result = 0;
        try {
            result = barcodeDetector.detect(content, byteArray, SAMPLE_LENGTH, SAMPLE_LENGTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HiLog.info(label, "字节流结果" + result);
        //释放侦测器
        result = barcodeDetector.release();

        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        //定义图片格式
        srcOpts.formatHint = "image/png";

        //创建图片源
        ImageSource imgSource = ImageSource.create(byteArray, srcOpts);

        //创建图像解码选项
        ImageSource.DecodingOptions decOPtions = new ImageSource.DecodingOptions();
        decOPtions.desiredPixelFormat = PixelFormat.ARGB_8888;

        //通过图片源创建PixelMap
        PixelMap pMap = imgSource.createPixelmap(decOPtions);
        //赋值到图片标签
        mTvResult.setVisibility(Component.HIDE);
        mImage.setPixelMap(pMap);
        //释放资源
        barcodeDetector.release();
        imgSource.release();
        if (pMap != null) {
            pMap.release();
            pMap = null;
        }
        VisionManager.destroy();
    }
}
